<template>
  <div class="min-h-screen p-4">
    <div class="max-w-4xl mx-auto">
      <!-- 顶部导航 -->
      <div class="flex justify-between items-center mb-8">
        <button @click="$emit('back')"
          class="px-4 py-2 bg-gray-500 text-white rounded hover:bg-gray-600 flex items-center gap-2">
          <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 19l-7-7m0 0l7-7m-7 7h18" />
          </svg>
          返回
        </button>
        <h1 class="text-3xl font-bold text-center">康威生命游戏</h1>
        <div class="w-24"></div>
      </div>

      <!-- 游戏控制面板 -->
      <div class="bg-white rounded-lg shadow-md p-4 mb-4">
        <div class="flex flex-wrap gap-3.5 items-center">
          <button @click="toggleGame" class="px-3 py-2 bg-blue-500 text-white rounded hover:bg-blue-600">
            {{ isRunning ? '暂停' : '开始' }}
          </button>

          <button @click="resetGame" class="px-3.5 py-2 bg-gray-500 text-white rounded hover:bg-gray-600">
            重置
          </button>

          <button @click="clearGrid" class="px-3.5 py-2 bg-red-500 text-white rounded hover:bg-red-600">
            清空
          </button>

          <button @click="$emit('showPatterns')" class="px-3.5 py-2 bg-green-500 text-white rounded hover:bg-green-600">
            预设图案
          </button>
          <div class="flex items-center gap-2">
            <label>速度:</label>
            <input type="range" v-model="speed" min="100" max="1000" step="100" class="w-32">
            <span>{{ speed }}ms</span>
          </div>
          <div class="flex items-center gap-2">
            <label>网格大小:</label>
            <input type="number" v-model="gridSize" min="10" max="100" class="w-20 px-2 py-1 border rounded">
          </div>
          <button @click="handleSwitchPattern" class="px-3.5 py-2 bg-purple-500 text-white rounded hover:bg-purple-600">
            {{ currentPattern?.name || '单个细胞' }}
          </button>
        </div>
      </div>

      <!-- 游戏画布 -->
      <div class="bg-white rounded-lg shadow-md p-4">
        <canvas ref="canvas" @mousedown="startDrawing" @mousemove="draw" @mouseup="stopDrawing"
          @mouseleave="stopDrawing" class="w-full border rounded"></canvas>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch } from 'vue'
import { GameOfLife } from '../game'
import { getCurrentPattern, switchCurrentPattern ,setCurrentPattern} from '../store/patternStore'

defineEmits(['back', 'showPatterns', 'switchCurrentPattern'])

const canvas = ref(null)
const game = ref(null)
const isRunning = ref(false)
const speed = ref(500)
const gridSize = ref(50)
const shouldRandomize = ref(true)
let animationFrame = null
let isDrawing = false
let lastDrawTime = 0
const DRAW_INTERVAL = 16 // 约60fps

// 当前选中的图案
const currentPattern = ref(null)

// 保存游戏状态
const saveGameState = () => {
  if (!game.value) return
  const gameState = {
    grid: game.value.grid.map(row => [...row]),
    gridSize: gridSize.value,
    speed: speed.value,
    isRunning: isRunning.value
  }
  localStorage.setItem('gameState', JSON.stringify(gameState))
  console.log('GameBoard.vue: 已保存游戏状态')
}

// 恢复游戏状态
const restoreGameState = () => {
  const savedState = localStorage.getItem('gameState')
  if (!savedState) return

  const gameState = JSON.parse(savedState)
  gridSize.value = gameState.gridSize
  speed.value = gameState.speed
  isRunning.value = gameState.isRunning

  const ctx = canvas.value.getContext('2d')
  game.value = new GameOfLife(gridSize.value, gridSize.value)
  game.value.grid = gameState.grid.map(row => [...row])
  
  resizeCanvas()
  drawGrid()
  console.log('GameBoard.vue: 已恢复游戏状态')
}

// 监听当前图案变化
watch(() => getCurrentPattern(), (newPattern) => {
  currentPattern.value = newPattern
  if (newPattern) {
    console.log('GameBoard.vue: 收到新图案', {
      patternName: newPattern.name,
      patternCategory: newPattern.category
    })
  }
}, { immediate: true })

// 初始化游戏
const initGame = () => {
  const ctx = canvas.value.getContext('2d')
  game.value = new GameOfLife(gridSize.value, gridSize.value)
  setCurrentPattern(null)
  resizeCanvas()
  if (shouldRandomize.value) {
    game.value.randomize()
  }
  drawGrid()
}

// 调整画布大小
const resizeCanvas = () => {
  const container = canvas.value.parentElement
  const size = Math.min(container.clientWidth - 32, 800)
  // 使用整数像素值
  canvas.value.width = Math.floor(size)
  canvas.value.height = Math.floor(size)
}

// 绘制网格
const drawGrid = () => {
  if (!game.value) return

  const ctx = canvas.value.getContext('2d')
  const cellSize = canvas.value.width / gridSize.value

  // 使用整数像素值避免模糊
  const width = Math.floor(canvas.value.width)
  const height = Math.floor(canvas.value.height)

  ctx.clearRect(0, 0, width, height)

  // 绘制网格线
  ctx.strokeStyle = '#ddd'
  ctx.lineWidth = 0.5

  for (let i = 0; i <= gridSize.value; i++) {
    const pos = Math.floor(i * cellSize)
    ctx.beginPath()
    ctx.moveTo(pos, 0)
    ctx.lineTo(pos, height)
    ctx.stroke()

    ctx.beginPath()
    ctx.moveTo(0, pos)
    ctx.lineTo(width, pos)
    ctx.stroke()
  }

  // 绘制细胞
  ctx.fillStyle = '#000'
  for (let y = 0; y < gridSize.value; y++) {
    for (let x = 0; x < gridSize.value; x++) {
      if (game.value.grid[y][x]) {
        const cellX = Math.floor(x * cellSize)
        const cellY = Math.floor(y * cellSize)
        const cellWidth = Math.ceil(cellSize) - 1
        const cellHeight = Math.ceil(cellSize) - 1
        ctx.fillRect(cellX, cellY, cellWidth, cellHeight)
      }
    }
  }
}

// 游戏循环
const gameLoop = () => {
  if (!isRunning.value) return

  game.value.nextGeneration()
  drawGrid()

  animationFrame = setTimeout(() => {
    gameLoop()
  }, speed.value)
}

// 开始/暂停游戏
const toggleGame = () => {
  isRunning.value = !isRunning.value
  if (isRunning.value) {
    gameLoop()
  } else {
    clearTimeout(animationFrame)
  }
}

// 停止游戏
const stopGame = () => {
  isRunning.value = false
  clearTimeout(animationFrame)
}

// 重置游戏
const resetGame = () => {
  isRunning.value = false
  clearTimeout(animationFrame)
  shouldRandomize.value = true
  game.value.randomize()
  drawGrid()
}

// 清空网格
const clearGrid = () => {
  isRunning.value = false
  clearTimeout(animationFrame)
  shouldRandomize.value = false
  // 清空所有细胞
  for (let y = 0; y < gridSize.value; y++) {
    for (let x = 0; x < gridSize.value; x++) {
      game.value.grid[y][x] = false
    }
  }
  
  drawGrid()
}

// 监听网格大小变化
watch(gridSize, () => {
  shouldRandomize.value = true
  initGame()
})

// 鼠标绘制相关方法
const startDrawing = (e) => {
  isDrawing = true
  const rect = canvas.value.getBoundingClientRect()
  const x = e.clientX - rect.left
  const y = e.clientY - rect.top
  const cellSize = canvas.value.width / gridSize.value
  const gridX = Math.floor(x / cellSize)
  const gridY = Math.floor(y / cellSize)

  if (gridX >= 0 && gridX < gridSize.value && gridY >= 0 && gridY < gridSize.value) {
    if (currentPattern.value) {
      // 如果有选中的图案，绘制图案
      const pattern = currentPattern.value
      const patternHeight = pattern.pattern.length
      const patternWidth = pattern.pattern[0].length
      const startX = gridX - Math.floor(patternWidth / 2)
      const startY = gridY - Math.floor(patternHeight / 2)

      // 绘制图案
      for (let py = 0; py < patternHeight; py++) {
        for (let px = 0; px < patternWidth; px++) {
          const targetX = startX + px
          const targetY = startY + py
          if (targetX >= 0 && targetX < gridSize.value && targetY >= 0 && targetY < gridSize.value) {
            game.value.grid[targetY][targetX] = pattern.pattern[py][px] === 1
          }
        }
      }
    } else {
      // 如果没有选中的图案，切换单个细胞状态
      game.value.grid[gridY][gridX] = !game.value.grid[gridY][gridX]
    }
    drawGrid()
  }
}

const draw = (e) => {
  if (!isDrawing) return

  const now = Date.now()
  if (now - lastDrawTime < DRAW_INTERVAL) return
  lastDrawTime = now

  const rect = canvas.value.getBoundingClientRect()
  const x = e.clientX - rect.left
  const y = e.clientY - rect.top
  const cellSize = canvas.value.width / gridSize.value
  const gridX = Math.floor(x / cellSize)
  const gridY = Math.floor(y / cellSize)

  if (gridX >= 0 && gridX < gridSize.value && gridY >= 0 && gridY < gridSize.value) {
    if (currentPattern.value) {
      // 如果有选中的图案，绘制图案
      const pattern = currentPattern.value
      const patternHeight = pattern.pattern.length
      const patternWidth = pattern.pattern[0].length
      const startX = gridX - Math.floor(patternWidth / 2)
      const startY = gridY - Math.floor(patternHeight / 2)

      // 绘制图案
      for (let py = 0; py < patternHeight; py++) {
        for (let px = 0; px < patternWidth; px++) {
          const targetX = startX + px
          const targetY = startY + py
          if (targetX >= 0 && targetX < gridSize.value && targetY >= 0 && targetY < gridSize.value) {
            game.value.grid[targetY][targetX] = pattern.pattern[py][px] === 1
          }
        }
      }
    } else {
      // 如果没有选中的图案，切换单个细胞状态
      game.value.grid[gridY][gridX] = !game.value.grid[gridY][gridX]
    }
    drawGrid()
  }
}

const stopDrawing = () => {
  isDrawing = false
}

// 监听窗口大小变化
const handleResize = () => {
  resizeCanvas()
  drawGrid()
}

// 处理切换图案
const handleSwitchPattern = () => {
  switchCurrentPattern()
  console.log('GameBoard.vue: 切换图案模式')
}

onMounted(() => {
  restoreGameState()
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  clearTimeout(animationFrame)
  saveGameState()
})

// 暴露方法给父组件
defineExpose({
  stopGame,
  initGame,
  saveGameState,
  restoreGameState
})
</script>